package com.ruoyi.wvp.service.impl;

import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.wvp.domain.AddressUnit;
import com.ruoyi.wvp.domain.SurveillanceEvent;
import com.ruoyi.wvp.service.IAddressUnitService;
import com.ruoyi.wvp.utils.PermissionUtil;
import jakarta.transaction.Transactional;
import jakarta.validation.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.wvp.mapper.SurveillanceMapper;
import com.ruoyi.wvp.domain.Surveillance;
import com.ruoyi.wvp.service.ISurveillanceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.enums.DeletedEnum;
import com.ruoyi.common.utils.StringUtils;

import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * AI摄像头Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-20
 */
@Service
@Slf4j
public class SurveillanceServiceImpl extends ServiceImpl<SurveillanceMapper, Surveillance> implements ISurveillanceService {
    @Autowired
    private SurveillanceMapper surveillanceMapper;

    @Autowired
    protected Validator validator;
    @Autowired
    protected IAddressUnitService addressUnitService;;

    /**
     * 查询AI摄像头
     *
     * @param id AI摄像头主键
     * @return AI摄像头
     */
    @Override
    public Surveillance selectSurveillanceById(String id) {
        return surveillanceMapper.selectSurveillanceById(id);
    }

    /**
     * 查询AI摄像头列表
     *
     * @param surveillance AI摄像头
     * @return AI摄像头
     */
    @Override
    public List<Surveillance> selectSurveillanceList(Surveillance surveillance) {
        return surveillanceMapper.selectSurveillanceList(surveillance);
    }

    /**
     * 新增AI摄像头
     *
     * @param surveillance AI摄像头
     * @return 结果
     */
    @Override
    public int insertSurveillance(Surveillance surveillance) {
        surveillance.setCreateTime(DateUtils.getNowDate());
        return surveillanceMapper.insertSurveillance(surveillance);
    }

    /**
     * 修改AI摄像头
     *
     * @param surveillance AI摄像头
     * @return 结果
     */
    @Override
    public int updateSurveillance(Surveillance surveillance) {
        surveillance.setUpdateTime(DateUtils.getNowDate());
        return surveillanceMapper.updateSurveillance(surveillance);
    }

    /**
     * 批量删除AI摄像头
     *
     * @param ids 需要删除的AI摄像头主键
     * @return 结果
     */
    @Override
    public int deleteSurveillanceByIds(String[] ids) {
        return surveillanceMapper.deleteSurveillanceByIds(ids);
    }

    /**
     * 删除AI摄像头信息
     *
     * @param id AI摄像头主键
     * @return 结果
     */
    @Override
    public int deleteSurveillanceById(String id) {
        return surveillanceMapper.deleteSurveillanceById(id);
    }


    @Override
    public Page<Surveillance> pageList(Page<Surveillance> page, Surveillance surveillance) {
        LambdaQueryWrapper<Surveillance> queryWrapper = getQueryWrapper(surveillance);
        return page(page, queryWrapper);
    }

    @Override
    public Surveillance getByMonitorCode(String monitorCode) {
        Wrapper<Surveillance> query=Wrappers.lambdaQuery(Surveillance.class)
                .eq(Surveillance::getDeviceNumber, monitorCode)
                .eq(Surveillance::getDeleted, DeletedEnum.NOMAL.getValue());
        return getOne(query,false);
    }

    @Override
    public List<Surveillance> listAll(Surveillance surveillance) {
        return list(getQueryWrapper(surveillance));
    }

    private LambdaQueryWrapper<Surveillance> getQueryWrapper(Surveillance surveillance) {
        LambdaQueryWrapper<Surveillance> queryWrapper = Wrappers.lambdaQuery(Surveillance.class);
        queryWrapper.eq(Surveillance::getDeleted, DeletedEnum.NOMAL.getValue());

        String sql = PermissionUtil.getDeptAddressUnitSql(SecurityUtils.getDeptId());
        queryWrapper.inSql(Surveillance::getCommunityCode,sql);
//        设备名称
        if (StringUtils.isNotEmpty(surveillance.getDeviceName())) {
            queryWrapper.like(Surveillance::getDeviceName, surveillance.getDeviceName());
        }


//        设备序列号
        if (StringUtils.isNotEmpty(surveillance.getSerialNumber())) {
            queryWrapper.like(Surveillance::getSerialNumber, surveillance.getSerialNumber());
        }


//        设备编号
        if (StringUtils.isNotEmpty(surveillance.getDeviceNumber())) {
            queryWrapper.like(Surveillance::getDeviceNumber, surveillance.getDeviceNumber());
        }


//        省份名称
        if (StringUtils.isNotEmpty(surveillance.getProviceName())) {
            queryWrapper.like(Surveillance::getProviceName, surveillance.getProviceName());
        }


//        省份编码
        if (StringUtils.isNotEmpty(surveillance.getProviceCode())) {
            queryWrapper.eq(Surveillance::getProviceCode, surveillance.getProviceCode());
        }


//        市名称
        if (StringUtils.isNotEmpty(surveillance.getCityName())) {
            queryWrapper.like(Surveillance::getCityName, surveillance.getCityName());
        }


//        市编号
        if (StringUtils.isNotEmpty(surveillance.getCityCode())) {
            queryWrapper.eq(Surveillance::getCityCode, surveillance.getCityCode());
        }


//        区名称
        if (StringUtils.isNotEmpty(surveillance.getAreaName())) {
            queryWrapper.like(Surveillance::getAreaName, surveillance.getAreaName());
        }

        if (StringUtils.isNotEmpty(surveillance.getAreaCodeHome())) {
            queryWrapper.eq(Surveillance::getAreaCode, surveillance.getAreaCodeHome());
        }
        if (StringUtils.isNotEmpty(surveillance.getStreetCodeHome())) {
            queryWrapper.eq(Surveillance::getStreetCode, surveillance.getStreetCodeHome());
        }


//        区编码
        if (StringUtils.isNotEmpty(surveillance.getAreaCode())) {
            queryWrapper.eq(Surveillance::getAreaCode, surveillance.getAreaCode());
        }


//        地址
        if (StringUtils.isNotEmpty(surveillance.getAddress())) {
            queryWrapper.like(Surveillance::getAddress, surveillance.getAddress());
        }
        //        地址
        if (StringUtils.isNotEmpty(surveillance.getStreetName())) {
            queryWrapper.like(Surveillance::getStreetName, surveillance.getStreetName());
        }


//        社区
        if (StringUtils.isNotEmpty(surveillance.getCommunity())) {
            queryWrapper.like(Surveillance::getCommunity, surveillance.getCommunity());
        }


//        小区名称
        if (StringUtils.isNotEmpty(surveillance.getResidentialName())) {
            queryWrapper.like(Surveillance::getResidentialName, surveillance.getResidentialName());
        }


//        ip地址
        if (StringUtils.isNotEmpty(surveillance.getIp())) {
            queryWrapper.eq(Surveillance::getIp, surveillance.getIp());
        }


//        物理地址
        if (StringUtils.isNotEmpty(surveillance.getMacAddress())) {
            queryWrapper.eq(Surveillance::getMacAddress, surveillance.getMacAddress());
        }


//        设备品牌
        if (StringUtils.isNotEmpty(surveillance.getDeviceBrand())) {
            queryWrapper.like(Surveillance::getDeviceBrand, surveillance.getDeviceBrand());
        }


//        设备型号
        if (StringUtils.isNotEmpty(surveillance.getDeviceModel())) {
            queryWrapper.like(Surveillance::getDeviceModel, surveillance.getDeviceModel());
        }


//        设备状态 1 在线 0 离线
        if (Objects.nonNull(surveillance.getDeviceStatus())) {
            queryWrapper.eq(Surveillance::getDeviceStatus, surveillance.getDeviceStatus());
        }


//        删除标识 0正常 1已删除
        if (Objects.nonNull(surveillance.getDeleted())) {
            queryWrapper.eq(Surveillance::getDeleted, surveillance.getDeleted());
        }


        return queryWrapper;
    }

    @Override
    public String importSurveillance(List<Surveillance> list, boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        List<AddressUnit> addressUnits = addressUnitService.listAll(new AddressUnit());
        Map<String, Long> addressUnitMap = addressUnits.stream().collect(Collectors.toMap(AddressUnit::getName, AddressUnit::getId));
        for (Surveillance item : list) {
            try {
                // 验证是否存在这个用户
                Surveillance u = getByMonitorCode(item.getDeviceNumber());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, item);
                    //设置区域编号和街道编号
                    setAreaCodeAndStreetCode(item, addressUnitMap);
                    item.setCreateBy(operName);
                    item.setCreateTime(new Date());
                    save(item);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、设备编号 " + item.getDeviceNumber() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, item);
                    item.setId(u.getId());
                    item.setUpdateBy(operName);
                    item.setUpdateTime(new Date());
                    //设置区域编号和街道编号
                    setAreaCodeAndStreetCode(item, addressUnitMap);
                    updateById(item);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、设备编号 " +item.getDeviceNumber() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、设备编号 " + item.getDeviceNumber() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、设备编号 " + item.getDeviceNumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Transactional(value = Transactional.TxType.REQUIRES_NEW)
    @Override
    public void updateBySerialNumber(List<String> deviceSerials, Integer workState) {
        if(CollectionUtils.isEmpty(deviceSerials)){
            return;
        }
        LambdaUpdateWrapper<Surveillance> updateWrapper = Wrappers.lambdaUpdate(Surveillance.class);
        updateWrapper.in(Surveillance::getSerialNumber,deviceSerials);
        updateWrapper.set(Surveillance::getDeviceStatus,workState);
        updateWrapper.set(Surveillance::getUpdateTime,new Date());
        updateWrapper.set(Surveillance::getUpdateBy,"系统");
        update(updateWrapper);
    }

    @Override
    public void updateBySerialNumber(String deviceSerial, Surveillance surveillance) {
        LambdaUpdateWrapper<Surveillance> updateWrapper = Wrappers.lambdaUpdate(Surveillance.class);
        updateWrapper.eq(Surveillance::getSerialNumber,deviceSerial);
        update(surveillance,updateWrapper);
    }

    private static void setAreaCodeAndStreetCode(Surveillance item, Map<String, Long> addressUnitMap) {
        Long areaCode = addressUnitMap.get(item.getAreaName());
        if(Objects.nonNull(areaCode)) {
            item.setAreaCode(areaCode.toString());
        }
        Long streetCode = addressUnitMap.get(item.getStreetName());
        if(Objects.nonNull(streetCode)) {
            item.setStreetCode(streetCode.toString());
        }
        Long communityCode = addressUnitMap.get(item.getCommunity());
        if(Objects.nonNull(communityCode)) {
            item.setCommunityCode(communityCode.toString());
        }
        Long residentialCode = addressUnitMap.get(item.getResidentialName());
        if(Objects.nonNull(residentialCode)) {
            item.setResidentialCode(residentialCode.toString());
        }
    }
}
